package com.ran.java_gobang_new.service;
import com.ran.java_gobang_new.JavaGobangNewApplication;
import com.ran.java_gobang_new.manager.OnlineManager;
import com.ran.java_gobang_new.manager.RoomManager;
import com.ran.java_gobang_new.pojo.dao.Room;
import com.ran.java_gobang_new.pojo.dao.UserInfo;
import com.ran.java_gobang_new.pojo.request.ChessRequest;
import com.ran.java_gobang_new.pojo.response.ChessResponse;
import com.ran.java_gobang_new.utils.JsonTrans;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: ran
 * Date: 2025-09-03
 * Time: 17:02
 */
// 处理游戏逻辑
@Slf4j
public class GameService {
    private static final int Row = 15;
    private static final int Col = 15;
    private OnlineManager onlineManager;
    private RoomManager roomManager;
   private UserInfoServise userInfoServise;

    public GameService() {
        onlineManager = JavaGobangNewApplication.context.getBean(OnlineManager.class);
        roomManager = JavaGobangNewApplication.context.getBean(RoomManager.class);
        userInfoServise = JavaGobangNewApplication.context.getBean(UserInfoServise.class);
    }

    // 初始化一个棋盘
    int[][] board = new int[Row][Col]; //



    // 下棋
    public void putChess(ChessRequest chessRequest,Integer row, Integer col) throws IOException {
        // 谁下的棋子, 获取当前下棋人在房间的 Session
        Integer userId = chessRequest.getUserId();
        Room room = roomManager.getRoomByUserId(userId);

        // 获取两个玩家的信息
        UserInfo user1 = room.getUser1();
        UserInfo user2 = room.getUser2();
        int chess = userId == user1.getUserId() ? 1 : 2; // 玩家1 就用1, 玩家2 就用2

        board[row][col] = chess; // 下完该棋子后, 判断胜负
        System.out.println("-----------------------------");
        print();

        int winner = handlerWinner(row,col,chess,user1,user2);

        // 准备返回对象
        ChessResponse response = new ChessResponse();
        response.setUserId(userId); // 谁下的棋子, 就返回给谁
        response.setChess(true);
        response.setRow(row);
        response.setCol(col);
        response.setWinner(winner);

        // 获取 两个玩家的 Session 会话
        WebSocketSession session1 = onlineManager.getRoomSession(user1.getUserId());
        WebSocketSession session2 = onlineManager.getRoomSession(user2.getUserId());
        // 玩家1 掉线
        if (session1 == null) {
            response.setWinner(user2.getUserId());
            log.info("玩家1 " + user1.getUserName() + " 掉线!");
            // 通知给用户2 他获胜了
            log.info("玩家2 " + user2.getUserName() + " 获胜!");
        }
        // 玩家2 掉线
        if (session2 == null) {
            response.setWinner( user1.getUserId());
            log.info("玩家2 " + user2.getUserName() + " 掉线!");
            // 通知给用户2 他获胜了
            log.info("玩家1 " + user1.getUserName() + " 获胜!");
        }

        // 该下棋的结果, 谁没有掉线发给谁
        if (session1 != null) {
            session1.sendMessage(JsonTrans.trans(response));
        }
        if (session2 != null) {
            session2.sendMessage(JsonTrans.trans(response));
        }

        // 没人掉线

        // 把结果通知给所有玩家
        // 分出胜负
        if (winner != 0) {
            log.info("正常删除房间,  room:{} ",room);
            // 更新玩家信息
            userInfoServise.win(winner);
            log.info("获胜者id: " + winner);
            Integer loserId = winner == user1.getUserId() ? user2.getUserId() : user1.getUserId();
            userInfoServise.lose(loserId);
            roomManager.remove(room,user1.getUserId(),user2.getUserId());
        }
    }

    void print() {
        for (int i = 0; i < Row; i++) {
            for (int j = 0; j < Col; j++) {
                System.out.print(board[i][j] + "  ");
            }
            System.out.println();
        }
    }




    // 只负责处理胜负
    private int handlerWinner(Integer row, Integer col, int chess, UserInfo user1, UserInfo user2) {
        // 横着连珠
        for (int r = row, c = col - 4; c <= col; c++) {
            try {
                if (board[r][c] == chess
                        && board[r][c + 1] == chess
                        && board[r][c + 2] == chess
                        && board[r][c + 3] == chess
                        && board[r][c + 4] == chess) {
                    return chess == 1 ? user1.getUserId() : user2.getUserId();
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                continue;
            }
        }
        // 竖着连珠
        for (int r = row - 4, c = col; r <= row; r++) {
            try {
                if (board[r][c] == chess
                        && board[r + 1][c] == chess
                        && board[r + 2][c] == chess
                        && board[r + 3][c] == chess
                        && board[r + 4][c] == chess) {
                    return chess == 1 ? user1.getUserId() : user2.getUserId();
                }
            } catch (ArrayIndexOutOfBoundsException e) {
                continue;
            }
        }
        // 反斜杠连珠
        for (int r = row - 4, c = col - 4; c <= col && r <= row;c++,r++) {
            try {
                if (board[r][c] == chess
                        && board[r + 1][c + 1] == chess
                        && board[r + 2][c + 2] == chess
                        && board[r + 3][c + 3] == chess
                        && board[r + 4][c + 4] == chess) {
                    return chess == 1 ? user1.getUserId() : user2.getUserId();
                }
            }catch (ArrayIndexOutOfBoundsException e) {
                continue;
            }

        }

        // 正斜杠
        for (int r = row - 4, c = col + 4; r <= row && c>= col; r++,c--) {
            try {
                if (board[r][c] == chess
                        && board[r + 1][c - 1] == chess
                        && board[r + 2][c - 2] == chess
                        && board[r + 3][c - 3] == chess
                        && board[r + 4][c - 4] == chess) {
                    return chess == 1 ? user1.getUserId() : user2.getUserId();
                }
            }catch (ArrayIndexOutOfBoundsException e) {
                continue;
            }

        }

        // 判断平局
        for (int i = 0; i < Row; i++) {
            for (int j = 0; j < Col; j++) {
                if (board[i][j] == 0) {
                    return 0; // 游戏未结束
                }
            }
        }
        return -1; // -1 代表平局
    }

}
